<template>
  <div class="app-container">
    <!-- 卡片食品介绍 -->
    <el-card class="box-card">
      <h3>食品上架</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <!-- <el-form-item label="食品编号" prop="foodId">
          <el-input v-model="goods.foodId" />
        </el-form-item> -->
        <el-form-item label="食品名称" prop="foodName">
          <el-input v-model="goods.foodName"/>
        </el-form-item>
        <el-form-item label="食品价格" prop="foodPrice">
          <el-input v-model="goods.foodPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="食品图片">
          <el-upload
            ref="upload"
            :on-change="handleChangeFile"
            :action="uploadPath"
            :show-file-list="false"
            list-type="picture"
            :headers="headers"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
            :auto-upload="true"
          >
            <img v-if="goods.foodImg" :src="goods.foodImg" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="所属商家编号">
          <el-input v-model="goods.businessId"></el-input>
        </el-form-item>

        <el-form-item label="食品备注">
          <el-input v-model="goods.remarks"/>
        </el-form-item>

        <el-form-item label="食品介绍">
          <editor :init="editorInit" v-model="goods.foodExplain"/>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 页面底部商家取消按钮 -->
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">上架</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {publishGoods, listCatAndBrand} from "@/api/goods/goods";
import {createStorage, uploadPath} from "@/api/system/storage";
import TinymceEditor from "@/components/TEditor.vue";
import {MessageBox} from "element-ui";
import {getToken} from "@/utils/auth";

export default {
  name: "GoodsCreate",
  components: {Editor: TinymceEditor},

  data() {
    return {
      fileList: [],
      uploadPath: process.env.VUE_APP_TARGET_API + "/upload", // 文件上传路径
      goods: {foodImg: ""}, // 食品信息
      // 验证规则
      rules: {
        foodName: [
          {required: true, message: "食品名称不能为空", trigger: "blur"},
        ],
      },
      // 富文本编辑器初始化
      editorInit: {
        language: "zh_CN", // 汉化
        language_url: "/tinymce/langs/zh_CN.js", // 这里的地址指向 public 目录下的路径
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        },
      },
    };
  },
  computed: {
    // 上传文件请求头添加Token
    headers() {
      return {
        "Shopping-Admin-Token": getToken(),
      };
    },
  },
  created() {
    // 页面数据初始化
    this.init();
  },

  methods: {
    handleChangeFile(file, fileList) {
      if (!file) return
      // suffix：后缀名 ，如：hello.jpg
      var suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const limit = file.size / 1024 / 1024 < 1
      if (suffix !== 'jpg' && suffix !== 'png' && suffix !== 'bmp') {
        this.$refs.upload.clearFiles()
        this.$message({
          message: '上传文件只能是 .jpg、.png、bmp格式!',
          type: 'warning'
        })
        return false
      }
      if (!limit) {
        this.$refs.upload.clearFiles()
        this.$message({
          message: '上传文件大小必须小于1MB!',
          type: 'warning'
        })
        return false
      }
    },
    // 获取数据
    init: function () {
      /* listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      }); */
    },

    // 取消食品上架钩子
    handleCancel: function () {
      this.$router.push({path: "/goods/index"});
    },
    // 上架食品 钩子
    handlePublish: function () {
      let food = {
        foodName: this.goods.foodName,
        foodImg: this.goods.foodImg,
        foodExplain: this.goods.foodExplain,
        foodPrice: this.goods.foodPrice,
        businessId: this.goods.businessId,
        remarks: this.goods.remarks,
      };
      // 调用接口
      publishGoods(food)
        .then((response) => {
          console.log("---------新增食品成功，返回数据：%o", response);
          this.$notify.success({
            title: "成功",
            message: "创建成功",
          });
          this.$router.push({path: "/goods/index"});
        })
        .catch((response) => {
          console.log("---------新增食品失败，返回数据：%o", response);
          MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
            confirmButtonText: "确定",
            type: "error",
          });
        });
    },

    // 食品图片上传之后的回调函数
    uploadPicUrl: function (response) {
      let fm = process.env.VUE_APP_IMAGE_SHOW_FORM;
      console.log("----fm:" + fm);
      if ("db" == fm) {
        this.goods.foodImg = response.data.url;
      } else if ("file" == fm) {
        this.goods.foodImg = process.env.VUE_APP_TARGET_API + response.data.url;
      }
    },
    // 上传文件个数限制
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!",
      });
    },
  },
};
</script>
